// uniCloud/cloudfunctions/userRegister/index.js
exports.main = async (event, context) => {
  try {
    const { account, password, nickName } = event;
    if (!account || !password || !nickName) {
      return { code: 400, msg: "参数不能为空" };
    }

    const db = uniCloud.database();
    const accountsCol = db.collection("Accounts");
    const userInfoCol = db.collection("UserInfo");

    // 1. 检查账号是否存在
    const exists = await accountsCol.where({ account }).get();
    if (exists.data.length > 0) {
      return { code: 400, msg: "用户名已被占用" };
    }

    // 2. 插入 Accounts 表
    const accountsRes = await accountsCol.add({
      account,
      password,
      nickName,
      createTime: new Date().toISOString()
    });
    const accountId = accountsRes.id; // 获取 Accounts 表的记录ID

    // 3. 同步插入 UserInfo 表（关联 Accounts 表的ID）
    await userInfoCol.add({
      account_id: accountId, // 关联字段（对应 Accounts 表的 _id）
      nickName,
      avatar: "/static/default-avatar.png", // 默认头像
      createTime: new Date().toISOString()
    });

    return { code: 200, msg: "注册成功", data: { accountId } };
  } catch (e) {
    return { code: 500, msg: "注册失败", error: e.message };
  }
};